<template>
  <div class="card_container">
    <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
      <template #content>
        <span>{{ t('club_page_pjlb') }} - {{ state.game_type == 49? t('club_page_49') : t('club_page_47') }}</span>
      </template>
      <template #left>
        <img src="/imgs/club/arrow_left.png" alt="" @click="router.go(-1)" class="arrow_left" />
      </template>
      <template #right>
        <img src="/imgs/club/add.webp" alt="" @click="onSubmitCreate" class="add" />
      </template>
    </nut-navbar>
    <nut-tabs @change="tabChange" v-model="state.play_type" title-scroll title-gutter="10" v-if="activeTabList">
      <nut-tab-pane :title="item.name" :pane-key="item.id" v-for="item in activeTabList" :key="item.id">
        <!-- 轮播 -->
        <!-- <nut-swiper
            :init-page="0"
            :auto-play="3000"
            pagination-visible
            pagination-color="#426543"
            pagination-unselected-color="#808080"
            style="height: 124px"
            >
            <nut-swiper-item v-for="(item, index) in list" :key="index">
              <img :src="item" alt="" class="imgs" draggable="false" />
            </nut-swiper-item>
        </nut-swiper> -->
       
        <div class="list_con" :style="contentStyle()">
           <!-- 赛事 -->
          <template v-if="item.id === -1">
            <nut-infinite-loading v-model="infinityValue" load-more-txt=" "
              :has-more="hasMore" @load-more="onLoad(1)">
              <nut-empty v-if="result.tournamentList.length == 0" :description="t('nomore_data')"></nut-empty>
              <TournamentCard  :tournaments="result.tournamentList" />
            </nut-infinite-loading>
            
          </template>
          <!-- 牌局 -->
          <template v-else>
            <nut-infinite-loading v-model="infinityValue" load-more-txt=" "
              :has-more="hasMore" @load-more="onLoad(2)">
              <nut-empty v-if="result.gamblingList.length == 0" :description="t('nomore_data')"></nut-empty>
              <GmablingCard :gameType="state.game_type" :gamblingList="result.gamblingList" />
            </nut-infinite-loading>
          </template>
        </div>
      </nut-tab-pane>
    </nut-tabs>
    <!-- 底部 -->
    <div class="button_container">
      <div class="button_box">
        <span class="button_start" @click="handleStartClick">{{ t('club_page_ksks') }}</span>
        <span 
          v-if="state.play_type !== -1"
          :class="isFilterActive ? 'button_default_hove' : 'button_default'"
          @click="handleDefaultClick"
        >
          {{ t('club_page_kongwei') }}
        </span>
        <span class="button_filter" @click="handleFilterClick">
          <img src="/imgs/club/shaixuan.webp" alt="" class="add" />
        </span>
      </div>
    </div>

    <!-- 快速弹窗 -->
    <QuickStartModal
      v-model:visible="isShowApply"
      :close="onModalClose"
    />

    <!-- 筛选 -->
    <FilterBox 
      :isPopup="isPopup" 
      :close="closePopup" 
      :isType="state.game_type"
      :modesType="modesType"
      @submit="handleFilterSubmit"
    />

    <EventsFilterBox 
      :isEventsPopup="isEventsPopup" 
      :close="closeEventsPopup" 
      :isType="state.game_type"
      @submit="handleEventsFilterSubmit"
    />

    <!-- 悬浮框 -->
    <LevitateBox
      @checkGame="onGameClick"
      @miniClick="onSwitchGameClick"
    />
  </div>
</template>

<script lang="ts" setup>
// @ts-nocheck
import {  ref, reactive, onMounted, watch, computed } from 'vue';
import FilterBox from './filterBox.vue';
import EventsFilterBox from './eventsFilterBox.vue';
import LevitateBox from '../components/levitateBox.vue';
import GmablingCard from "@/components/gamblingCard.vue";
import TournamentCard from "../components/tournamentCard.vue";
import QuickStartModal from "@/components/quickStartModal.vue";

import {  useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

import { storeToRefs } from "pinia";
import pinia from "@/store/index";
import { User } from "@/store/user";
const { appHeight } = storeToRefs(User(pinia));

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { useI18n } from "vue-i18n";
const { t } = useI18n();

const state = reactive({
  club_id: 0, // 俱乐部ID "49"德州, "pdk"跑得快
  game_type: 0, // 游戏类型
  play_type: 0, // 玩法-德州
  min_buy: 0, // 买入最小
  max_buy: 0, // 买入最大
  big_blind: 0, // 盲注金额 -1表示全部。德州、跑得快
  player_count: 0, // 每桌人数上限
  blind_count: 0, // 开局盲注数量
  limit_bet_rule: 0, // 限注规则
  all_insurance: 0, // 全下保险功能
  min_carry_money: 0, // 最低携带金额
  min_bet: 0, // 底注 -1表示全部。跑得快
  win_rule: 0, // 输赢规则，
  min_take: 0, // 买入下限
  max_take: 0, // 买入上限
  small_blind: 0, // 小盲注
  max_blind: 0, // 大盲注
})
const infinityValue = ref(false);
const hasMore = ref(true);
const params: any = reactive({
  // 参数
  pageSize: 10,
  page: 1,
});
const result: any = reactive({
  // 结果
  total_page: 0,
  gamblingList: [],
  tournamentList: []
});
// const list = ref([
//   'https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg',
//   'https://storage.360buyimg.com/jdc-article/NutUItaro2.jpg',
//   'https://storage.360buyimg.com/jdc-article/welcomenutui.jpg',
//   'https://storage.360buyimg.com/jdc-article/fristfabu.jpg'
// ])
const eventsState = reactive<any>({
  game_type: 0, // 游戏类型
  start_time: {
    year: 0, 
    month: 0, 
    day: 0, 
    hour: 0, 
    minute: 0, 
    second: 0
  }, // 开始时间
  end_time: {
    year: 0, 
    month: 0, 
    day: 0, 
    hour: 0, 
    minute: 0, 
    second: 0
  }, // 结束时间
  tournament_type: -1, // 每桌人数上限
  page_index: 1, // 页码
})
const dzTabList = ref([
  {
    id: 0,
    name: t('club_page_tj'),
  },
  {
    id: 1,
    name: t('club_page_jd'),
  },
  {
    id: 2,
    name: t('club_page_dp'),
  },
  {
    id: -1,
    name: t('club_page_events'),
  }
]);

const pdkTabList = ref([
  {
    id: 0,
    name: t('club_page_tj'),
  },
  {
    id: -1,
    name: t('club_page_events'),
  }
]);
const modesType:any = ref({})

// 动态获取 tab 列表
const activeTabList = computed(() => {
  return state.game_type == 49 ? dzTabList.value : pdkTabList.value;
});

const onSubmitCreate = () => {
  router.push({ 
    path: "/club/createGamebling",
    query: { club_id: state.club_id }
  })
};


const contentStyle = () => {
  return window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone
    ? { height: `calc(${appHeight.value}px - 200px)` }
    : { height: `calc(${appHeight.value}px - 200px)` };
};

// 筛选条件金额区间
const getFilterCondition = () => {
  // @ts-ignore
  const req = NetPacket.req_get_filter_condition();
  req.game_type = state.game_type
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_get_filter_condition",
    callback: getFilterConditionHandle,
  });
};
// 牌局列表返回
const getFilterConditionHandle = (res: any) => {
  modesType.value = res
};

const tabChange = async (item: any) => {
  params.page = 1;
  infinityValue.value = false
  hasMore.value = true
  state.play_type = Number(item.paneKey)
  if(item.paneKey != -1) {
    result.gamblingList = []
    await getFilterDeskList()
  } else {
    result.tournamentList = []
    await getTorunametList()
  }
}

const isShowApply = ref(false);
const handleStartClick = () => {
  console.log("快速开始按钮被点击");
  isShowApply.value = true
}

const onModalClose = () => {
  isShowApply.value = false;
};

const isFilterActive = ref(false); 
const handleDefaultClick = () => {
  isFilterActive.value = !isFilterActive.value;
  if (isFilterActive.value) {
    result.gamblingList = result.gamblingList.filter(
      (item: any) => item.role_count < item.max_player
    );
  } else {
    loadOriginalData();
  }
}
 // 恢复数据逻辑
const loadOriginalData = () => {
  getFilterDeskList();
};

const isPopup = ref(false);
const isEventsPopup = ref(false);

const handleFilterClick = () => {
  if(state.play_type == -1) {
    isEventsPopup.value = true
  } else {
    isPopup.value = true
  }
}
const closePopup = () => {
  isPopup.value = false;
};
const closeEventsPopup = () => {
  isEventsPopup.value = false;
};

const handleFilterSubmit = async (item: any) => {
  state.player_count = item.player_count // 桌人数
  state.limit_bet_rule = item.limit_bet_rule// 限注规则-德州
  state.win_rule = item.win_rule // 输赢规则-跑得快
  state.small_blind = item.small_blind, // 小盲
  state.max_blind = item.max_blind // 大盲
  await resetData()
  await getFilterDeskList()
}

// 获取牌局列表
const getFilterDeskList = () => {
  infinityValue.value = true;
  const req = NetPacket.req_filter_desk();
  req.club_id = state.club_id
  req.game_type = state.game_type
  req.play_type = state.play_type
  req.min_buy = state.min_buy
  req.max_buy = state.max_buy
  req.big_blind = state.big_blind
  req.player_count = state.player_count
  req.blind_count = state.blind_count
  req.limit_bet_rule = state.limit_bet_rule
  req.all_insurance = state.all_insurance
  req.min_carry_money = state.min_carry_money
  req.min_bet = state.min_bet
  req.win_rule = state.win_rule
  req.page_index = params.page
  req.page_size = params.pageSize
  req.min_take = state.min_take
  req.max_take = state.max_take
  req.small_blind = state.small_blind
  req.max_blind = state.max_blind
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_filter_desk",
    callback: getFilterDeskListHandle,
  });
};
// 牌局列表返回
const getFilterDeskListHandle = (res: any) => {
  if (res.room_list.length < params.pageSize) {
    hasMore.value = false;
  } else {
    hasMore.value = true;
  }
  result.gamblingList = [...result.gamblingList, ...res.room_list];
  infinityValue.value = false;
};


const handleEventsFilterSubmit = async (item: any) => {
  eventsState.start_time = item.start_time // 开始时间
  eventsState.end_time = item.end_time, // 结束时间
  eventsState.tournament_type = item.tournament_type, // 游戏类型
  await getTorunametList()
}

// 赛事
const getTorunametList = async () => {
  //获取赛事列表
  infinityValue.value = true;
  const eventsList = NetPacket.req_filter_tournament();
  eventsList.game_type = eventsState.game_type
  eventsList.page_index = params.page
  eventsList.page_size = params.pageSize
  Object.assign(eventsList.start_time, eventsState.start_time) // 开始时间
  Object.assign(eventsList.end_time, eventsState.end_time) // 结束时间
  eventsList.tournament_type = eventsState.tournament_type, // 游戏类型
  PKwebsocket.instance.send(eventsList, true, {
    callbackName: "msg_notify_filter_tournament",
    callback: handleEventsList,
  });
}
const handleEventsList =  (res: any) => {
  if (res.tournm_list.length < params.pageSize) {
    hasMore.value = false;
  } else {
    hasMore.value = true;
  }
  result.tournamentList = [...result.tournamentList, ...res.tournm_list];
  infinityValue.value = false;
};

const onGameClick = (item: any) => {
  console.log("Selected game:", item.label);
}

const onSwitchGameClick = (game: { id: number; title: string }) => {
  console.log(`你点击了游戏：${game.title}`);
 }

const onLoad = (type: number) => {
  params.page++;
  if(type === 2) {
    getFilterDeskList();
  } else {
    getTorunametList()
  }
};

const resetData = () => {
  params.page = 1;
  result.gamblingList = [];
  result.tournamentList = [];
  infinityValue.value = false;
  hasMore.value = true;
};

watch(
  () => route.query.gameType,
  (newId) => {
    state.game_type = Number(newId)
    resetData()
  },
  { immediate: true }
);

onMounted(async () => {
  const { gameType, clubId } = route.query;
  state.game_type = Number(gameType)
  eventsState.game_type = Number(gameType)
  state.club_id = Number(clubId)
  state.play_type = 0
  await getFilterCondition();
  await getFilterDeskList();
});

</script>

<style scoped lang="scss">
.card_container {
  .arrow_left {
    width: 24px;
    height: 24px;
  }
  :deep(.nut-navbar__right) {
    padding: 0;
  }
  .add {
    width: 32px;
    height: 32px;
  }
  .imgs{
    height: 124px;
    width: 347px;
    
  }
  :deep(.nut-swiper) {
    width: 347px;
    border-radius: 8px;
    margin: 0 auto 10px;
  }

  :deep(.nut-tabs__titles) {
    height: 36px;
  }

  .list_con {
    width: 347px;
    margin: 0 auto;
    overflow: auto;
  }

  .button_container {
    width: 100%;
    height: 80px;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1;
    display: flex;
    align-items: center;
    background: #131232;
    border-radius: 8px 8px 0 0;

    .button_box {
      width: 347px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px; // 按钮间距

      .button_start {
        width: 142px;
        height: 40px;
        background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
        box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
        color: white;
        border-radius: 8px;
        padding: 10px 20px;
        color: #FFF;
        text-align: center;
        font-size: 14px;
        font-weight: 500;
      }

      .button_default {
        width: 142px;
        height: 40px;
        background: #282747;
        box-shadow: 0.5px 0.5px 1px 0px #4B4A6E inset;
        border-radius: 8px;
        padding: 10px 20px;
        color: #FFF;
        text-align: center;
        font-size: 14px;
        font-weight: 500;
      }

      .button_default_hove{
        width: 142px;
        height: 40px;
        border-radius: 8px;
        background: #8B8B8B;
        box-shadow: 0.5px 0.5px 1px 0px #D7D7D7 inset;
        padding: 10px 20px;
        color: #D2D2D2;
        text-align: center;
        font-size: 14px;
        font-weight: 500;
      }

      .button_filter {
        background-color: #282747;
        box-shadow: 0.5px 0.5px 1px 0px #4B4A6E inset;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        img {
          width: 18px;
          height: 18px;
        }
      }

      .button_filter {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px;
        font-size: 18px;
      }
    }
  }
  
}
.popup_body {
  color: #fff;
  padding: 10px;

  .game_container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 40px;
    padding: 20px;

    .game_item {
      text-align: center;
      color: #ffffff;

      .game_icon {
        width: 64px;
        height: 64px;
        display: block;
        border-radius: 12px;
        background-size: cover;
        background-position: center;
        margin-bottom: 10px;
      }

      .game_title {
        color: #FFF;
        font-size: 14px;
        font-weight: 400;
      }
    }
  }
}


</style>